package com.itheima.service;

import cn.hutool.core.util.ObjectUtil;
import com.itheima.api.SmsHomeAdvertiseApi;
import com.itheima.exception.ConsumerException;
import com.itheima.pojo.SmsHomeAdvertise;
import com.itheima.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.scanner.ScannerImpl;

import java.lang.reflect.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author pk
 * @date 2022/10/12/19:17
 */
@Service
public class SmsHomeAdvertiseService {


    @DubboReference
    private SmsHomeAdvertiseApi advertiseApi;

    /**
     * 添加广告功能
     *
     * @param advertise
     */
    public void saveAdvertise(SmsHomeAdvertise advertise) {
        //调用api添加
        advertiseApi.saveAdvertise(advertise);

    }

    /**
     * 分页查询广告
     *
     * @param
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageResult findAdvertise(String endTime, String name, Integer type, Integer pageNum, Integer pageSize) {

        SmsHomeAdvertise advertise = new SmsHomeAdvertise();
        if (ObjectUtil.isNotNull(endTime)) {
            try {
                advertise.setEndTime(new SimpleDateFormat("yyyy-MM-dd").parse(endTime));
                advertise.setName(name);
                advertise.setType(type);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        return advertiseApi.findAdvertise(advertise, pageNum, pageSize);

    }

    /**
     * 广告删除
     *
     * @param id
     */
    public void deleteAdvertise(Integer[] id) {
        List<Long> ids = Arrays.stream(id).map(e -> Long.valueOf(e)).collect(Collectors.toList());
        //调用api删除
        if (!advertiseApi.deleteAdvertise(ids)) {
            //删除失败则抛出异常
            throw new ConsumerException("网络繁忙请刷新重试");
        }
    }


    /**
     * 修改上下线状态
     *
     * @param id
     * @param status
     */
    public void updateStatus(Long id, Integer status) {

        //调用api根据id查询广告实例
        SmsHomeAdvertise advertise = advertiseApi.findAdvertiseById(id);
        if (advertise != null) {
            if (status != null)
                advertise.setStatus(status);
        }
        //修改状态
        advertiseApi.updateStatus(advertise);
    }

    /**
     * 广告修改
     *
     * @param id
     * @param advertise
     */
    public void updateAdvertise(Long id, SmsHomeAdvertise advertise) {
        //组装参数
        advertise.setId(id);
        //修改状态
        advertiseApi.updateStatus(advertise);

    }

    /**
     * 查询广告详情
     *
     * @param id
     * @return
     */
    public SmsHomeAdvertise queryAdvertise(Long id) {
        return advertiseApi.findAdvertiseById(id);
    }


}
